package org.example.lock;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockExample {

    private final ReentrantLock lock = new ReentrantLock();

    public void someMethod() {
        lock.lock();
        try {
            // 执行临界区代码
            System.out.println(Thread.currentThread().getName() + " has acquired the lock.");
            // 执行业务逻辑
            Thread.sleep(1000); // 模拟耗时操作
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockExample example = new ReentrantLockExample();

        Thread thread1 = new Thread(() -> example.someMethod(), "Thread-1");
        Thread thread2 = new Thread(() -> example.someMethod(), "Thread-2");

        thread1.start();
        thread2.start();
    }
}